package com.onlyxiahui.common.utils.base.security;

import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.util.Base64;

/**
 * 
 * Description 签名和验证<br>
 * Date 2020-11-09 15:02:46<br>
 * 
 * @author XiaHui [onlovexiahui@qq.com]<br>
 * @since 1.0.0
 */
public class SecuritySignatureUtil {

	/**
	 * 
	 * Description 签名<br>
	 * Date 2020-11-10 13:37:16<br>
	 * 
	 * @param content
	 * @param key
	 * @return
	 * @since 1.0.0
	 */
	public static String signatureSha1WithRsa(String content, PrivateKey key) {
		String sign = null;
		if (null != content) {
			try {
				// 获取Signature实例，指定签名算法(与之前一致)
				Signature signature = Signature.getInstance("SHA1WithRSA");
				// 加载公钥
				signature.initSign(key);
				// 更新原数据
				signature.update(content.getBytes("UTF-8"));
				// 公钥验签（true-验签通过；false-验签失败）
				byte[] bytes = signature.sign();
				// sign = base64Encoder.encode(bytes);
				sign = Base64.getEncoder().encodeToString(bytes);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return sign;
	}

	/**
	 * 
	 * Description 验证签名<br>
	 * Date 2020-11-10 13:37:30<br>
	 * 
	 * @param content
	 * @param sign
	 * @param key
	 * @return
	 * @since 1.0.0
	 */
	public static boolean verifySha1WithRsa(String content, String sign, PublicKey key) {
		boolean mark = false;
		try {
			// 获取Signature实例，指定签名算法(与之前一致)
			Signature signature = Signature.getInstance("SHA1WithRSA");
			// 加载公钥
			signature.initVerify(key);
			// 更新原数据
			signature.update(content.getBytes("UTF-8"));
			// 公钥验签（true-验签通过；false-验签失败）
			// mark = signature.verify(base64Decoder.decodeBuffer(sign));
			mark = signature.verify(Base64.getDecoder().decode(sign));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return mark;
	}
}
